<template>
  <v-card-text>
    <!-- Step 1: 基本信息（邮箱、密码、真实姓名） -->
    <div v-if="step === 1">
      <v-form ref="formRef" @submit.prevent="onSubmitStep1">
        <v-text-field
          v-model="email"
          clearable
          data-testid="account-outlined-email"
          density="comfortable"
          label="邮箱"
          :prepend-inner-icon="mdiEmail"
          rounded="lg"
          :rules="[rules.required, rules.email]"
          variant="outlined"
        />
        <v-text-field
          v-model="password"
          :append-inner-icon="showPassword ? mdiEyeOff : mdiEye"
          class="mt-1"
          data-testid="account-outlined-password"
          density="comfortable"
          label="密码"
          :prepend-inner-icon="mdiLock"
          rounded="lg"
          :rules="[rules.required, rules.pwd]"
          :type="showPassword ? 'text' : 'password'"
          variant="outlined"
          @click:append-inner="showPassword = !showPassword"
        />
        <v-text-field
          v-model="name"
          class="mt-1"
          data-testid="account-outlined-newname"
          density="comfortable"
          label="真实姓名"
          :prepend-inner-icon="mdiAccount"
          rounded="lg"
          :rules="[rules.required]"
          variant="outlined"
        />

        <v-btn
          block
          class="mt-4"
          color="primary"
          data-testid="account-outlined-submit"
          :loading="loading"
          size="large"
          type="submit"
        >
          发送验证码
        </v-btn>
        <div class="d-flex justify-end mt-2">
          <v-btn
            class="px-1"
            data-testid="account-outlined-gologin"
            density="comfortable"
            variant="text"
            @click="emit('go-login')"
          >
            已有账号？去登录
          </v-btn>
        </div>
      </v-form>
    </div>

    <!-- Step 2: 邮箱验证码 -->
    <div v-else>
      <div class="text-body-2 text-medium-emphasis mb-2">
        验证码已发送至 <strong>{{ email }}</strong
        >，请在 5 分钟内输入
      </div>
      <v-otp-input
        v-model="code"
        autofocus
        class="mt-1"
        :disabled="loading"
        :length="6"
        type="text"
      />
      <div v-if="codeError" class="text-error text-caption mt-1 text-center">{{ codeError }}</div>
      <div class="d-flex ga-2 mt-2 justify-center">
        <v-btn
          color="primary"
          data-testid="account-outlined-onVerifyCode"
          :loading="loading"
          @click="onVerifyCode"
          >验证并注册</v-btn
        >
        <v-btn
          data-testid="account-outlined-resend"
          :disabled="resendIn > 0 || loading"
          :prepend-icon="mdiReload"
          variant="tonal"
          @click="resend"
        >
          重新发送
          <span v-if="resendIn > 0"> ({{ resendIn }}s)</span>
        </v-btn>
        <v-btn data-testid="account-outlined-backToInfo" variant="text" @click="backToInfo"
          >返回修改信息</v-btn
        >
      </div>
    </div>
  </v-card-text>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, ref } from 'vue'
import { mdiAccount, mdiEmail, mdiEye, mdiEyeOff, mdiLock, mdiReload } from '@mdi/js'
import { authState } from '@/windows/layoutBrowser/stores/auth'
import { useTabStore } from '@/windows/layoutBrowser/stores/tab'

const emit = defineEmits<{ (e: 'go-login'): void }>()

const step = ref<1 | 2>(1)
const loading = ref(false)

const email = ref('')
const password = ref('')
const name = ref('')

const showPassword = ref(false)

const code = ref('')
const codeError = ref('')
const resendIn = ref(0)
let timer: any | null = null
const serverCode = ref('')

const rules = {
  required: (v: string) => (!!v && v.length > 0) || '必填项',
  email: (v: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) || '邮箱格式不正确',
  pwd: (v: string) => v.length >= 6 || '至少6位密码'
}

const formRef = ref()

async function onSubmitStep1() {
  const res = await formRef.value?.validate?.()
  if (!res || !res.valid) return
  loading.value = true
  await sendVerificationEmail()
  step.value = 2
  loading.value = false
}

async function onVerifyCode() {
  codeError.value = ''
  if (!code.value || code.value.length !== 6) {
    codeError.value = '请输入6位验证码'
    return
  }
  loading.value = true
  await new Promise(r => setTimeout(r, 400))
  if (code.value !== serverCode.value) {
    loading.value = false
    codeError.value = '验证码不正确'
    return
  }
  stopCountdown()
  await completeRegistration()
}

async function sendVerificationEmail() {
  // 模拟发送邮件并生成验证码
  await new Promise(r => setTimeout(r, 800))
  serverCode.value = String(Math.floor(100_000 + Math.random() * 900_000))
  // console.log('[Mock] 邮箱验证码:', serverCode.value)
  startCountdown()
}

function resend() {
  if (resendIn.value > 0 || loading.value) return
  loading.value = true
  sendVerificationEmail().then(() => (loading.value = false))
}

function backToInfo() {
  step.value = 1
  code.value = ''
  codeError.value = ''
  serverCode.value = ''
  stopCountdown()
}

function startCountdown() {
  stopCountdown()
  resendIn.value = 60
  timer = setInterval(() => {
    resendIn.value -= 1
    if (resendIn.value <= 0) {
      stopCountdown()
    }
  }, 1000)
}

function stopCountdown() {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

async function completeRegistration() {
  const fallbackName = (() => {
    const first = email.value.split('@')[0]
    return (first ?? email.value) || email.value
  })()
  authState.set({
    isLoggedIn: true,
    user: {
      id: 'u_reg_' + Date.now(),
      name: name.value || fallbackName,
      email: email.value
    },
    provider: 'password'
  })
  try {
    const tabStore = useTabStore()
    tabStore.closeAllTabs()
    tabStore.setActiveTab(0)
  } catch {}
  loading.value = false
}

onBeforeUnmount(() => stopCountdown())
</script>
